from django.db.models.query import QuerySet
from django.shortcuts import HttpResponse
from django.http.response import JsonResponse
from .models import Lecture, Tag
import datetime
from math import ceil

# OK: 我这应该没办法接 info、other、special，直接把这几个参数拼起来给我
# OK: campus 要不直接做成 enum

# OK: 加下可选的分页参数
prefix = "https://www.yuque.com/greatnju/lecture/"
weekStr = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]


def getTag(request):
    tags = Tag.objects.all()
    data = [x.name for x in tags]
    return JsonResponse({"data": data}, json_dumps_params={"ensure_ascii": False})


def splitData(lectures, limit, page):
    length = len(lectures)
    total_page = ceil(length / limit) if limit > 0 else 0
    lectures = lectures[limit * (page - 1) : min(limit * page, length)]
    data = [
        {
            "id": x.id,
            "title": x.title,
            "teacher": x.teacher,
            "classroom": x.classroom,
            "tag": "，".join(x.tag_list),
            "startTime": x.combineStart,
            "endTime": x.combineEnd,
            "startIndex": x.startIndex,
            "endIndex": x.endIndex,
            "accurate": x.accurate,
            "info": "时间：{}（{}） {}-{}\n\n讲座内容：{}\n\n特殊要求：{}\n\n其他信息：{}\n\n详情链接：{}".format(
                x.date,
                weekStr[x.date.weekday()],
                x.startTime.strftime("%H:%M"),
                x.endTime.strftime("%H:%M"),
                x.info,
                x.special,
                x.other,
                prefix + x.slug,
            ),
            "department": x.department,
            "count": x.count,
        }
        for x in lectures
    ]
    return {"data": data, "total_page": total_page}


def sortData(lectures):
    now = datetime.datetime.now()
    first, second = [], []
    for x in lectures:
        x.combineStart = datetime.datetime.combine(x.date, x.startTime)
        x.combineEnd = datetime.datetime.combine(x.date, x.endTime)
        if x.combineEnd > now:
            first.append(x)
        else:
            second.append(x)
    first.sort(key=lambda x: x.combineStart)
    second.sort(key=lambda x: x.combineStart, reverse=True)
    return first + second


def getAll(request):
    # tag是标签列表
    if "tag" in request.GET:
        tag = request.GET.getlist("tag")
        result = [Tag.objects.filter(name=t).first().lecture_set.all() for t in tag]
        # 至少有一个tag
        lectures = result[0]
        for i in range(1, len(result)):
            lectures &= result[i]
    else:
        lectures = Lecture.objects.all()

    lectures = sortData(lectures)

    # ~~这我没想好 不过除了“具体时间”~~ 先不传 可能app端内处理更灵活一点
    # 估计也得给我传一份「转义后是第几节课」方便我直接进行课程导入
    # 这部分字段不需要录入的人员录入，而是在落库或者请求的时候直接计算
    # 举个例子：14:00-16:00的讲座，需要额外传给我 是 5-6 节
    # 对于非严格时间的，例如 14:30-15:30 的讲座，也需要传给我 5-6 节
    # 另外还需要有个字段，表明这个时间是「准确的」还是「拟合出来的」
    # P.S: 日期可以我自己算

    limit = int(request.GET.get("limit", len(lectures)))
    page = int(request.GET.get("page", 1))

    return JsonResponse(
        splitData(lectures, limit, page), json_dumps_params={"ensure_ascii": False}
    )


# OK: 给个搜索接口，名还没想好，瞎起的
# 是不是可以一个里面直接做个标题、老师、校区、描述、时间的混合搜索吧 我传可选参数按参数条件给我结果
# 这样如果用户用复合筛选也能给到结果，也不用getDate了
# title,teacher,campus,info,year,month,day
def getLecturesBySearch(request):
    search = {
        "title__contains": request.GET.get("title", None),
        "teacher__contains": request.GET.get("teacher", None),
        "info__contains": request.GET.get("info", None),
        "date__year": int(request.GET.get("year")) if "year" in request.GET else None,
        "date__month": int(request.GET.get("month"))
        if "month" in request.GET
        else None,
        "date__day": int(request.GET.get("day")) if "day" in request.GET else None,
    }
    for x in list(search.keys()):
        if search[x] is None:
            del search[x]

    lectures = sortData(Lecture.objects.filter(**search))
    limit = int(request.GET.get("limit", len(lectures)))
    page = int(request.GET.get("page", 1))

    return JsonResponse(
        splitData(lectures, limit, page), json_dumps_params={"ensure_ascii": False}
    )


# OK: 给个「记录有多少人添加了这个讲座」的功能
# 添加成功之后我调用这个接口往数据库里自增
def addCount(request):
    index = int(request.GET.get("id"))
    t = Lecture.objects.filter(id=index)
    t.update(count=t[0].count + 1)
    return HttpResponse()
